const db = require('../config/database');
const { encrypt, decrypt } = require('../utils/encryption');

class User {
  constructor(data = {}) {
    this.id = data.id;
    this.name = data.name;
    this.phone = data.phone;
    this.id_card = data.id_card;
    this.email = data.email;
    this.province = data.province;
    this.city = data.city;
    this.district = data.district;
    this.address = data.address;
    this.is_anonymous = data.is_anonymous || 0;
    this.ip_address = data.ip_address;
    this.user_agent = data.user_agent;
    this.created_at = data.created_at;
    this.updated_at = data.updated_at;
    this.township = data.township;
  }

  // 创建用户
  async create() {
    try {
      console.log('User.create called. is_anonymous:', this.is_anonymous, 'name:', this.name);
      // 数据验证和长度限制
      if (!this.is_anonymous) { // 只有在非匿名用户时才验证姓名和手机号
      if (!this.name || this.name.trim().length === 0) {
        throw new Error('姓名不能为空');
      }
      
      // 限制姓名长度（考虑加密后的长度）
      if (this.name.length > 15) {
        throw new Error('姓名长度不能超过15个字符');
      }
      
      // 验证手机号格式
      if (!this.phone || !/^1[3-9]\d{9}$/.test(this.phone)) {
        throw new Error('手机号格式不正确');
        }
      }
      
      // 处理地区信息 - 支持新的township字段
      let province = this.province || '江西省';
      let city = this.city || '宜春市';
      let district = this.district || '袁州区';
      
      // 如果有township字段，查询对应的地区信息
      if (this.township) {
        try {
          const region = await db.findOne('regions', { id: this.township });
          if (region) {
            district = region.name;
            // 可以根据需要设置省市信息
            province = '江西省';
            city = '宜春市';
          }
        } catch (e) {
          console.warn('查询地区信息失败:', e.message);
        }
      }

      // 加密敏感信息
      const encryptedData = {
        name: this.name ? encrypt(this.name.trim()) : null,
        phone: this.phone ? encrypt(this.phone.trim()) : null,
        id_card: this.id_card ? encrypt(this.id_card.trim()) : null,
        email: this.email ? this.email.trim() : null,
        province: province,
        city: city,
        district: district,
        address: this.address ? this.address.trim() : null,
        is_anonymous: this.is_anonymous,
        ip_address: this.ip_address,
        user_agent: this.user_agent
      };

      const result = await db.insert('users', encryptedData);
      this.id = result.insertId;
      return this;
    } catch (error) {
      console.error('创建用户失败:', error);
      throw new Error(`创建用户失败: ${error.message}`);
    }
  }

  // 根据ID查找用户
  static async findById(id) {
    try {
      const userData = await db.findOne('users', { id });
      if (!userData) return null;

      // 解密敏感信息
      userData.name = decrypt(userData.name);
      userData.phone = decrypt(userData.phone);
      if (userData.id_card) {
        userData.id_card = decrypt(userData.id_card);
      }

      return new User(userData);
    } catch (error) {
      throw new Error(`查找用户失败: ${error.message}`);
    }
  }

  // 根据电话查找用户
  static async findByPhone(phone) {
    try {
      // 由于电话是加密的，需要查询所有用户然后逐个解密对比
      const users = await db.findMany('users');
      for (const userData of users) {
        try {
          const decryptedPhone = decrypt(userData.phone);
          if (decryptedPhone === phone) {
            userData.name = decrypt(userData.name);
            userData.phone = decryptedPhone;
            if (userData.id_card) {
              userData.id_card = decrypt(userData.id_card);
            }
            return new User(userData);
          }
        } catch (e) {
          // 解密失败，跳过该记录
          continue;
        }
      }
      return null;
    } catch (error) {
      throw new Error(`查找用户失败: ${error.message}`);
    }
  }

  // 获取用户列表（管理员用）
  static async getList(options = {}) {
    try {
      const { page = 1, pageSize = 20, province, city } = options;
      const offset = (page - 1) * pageSize;

      let conditions = {};
      if (province) conditions.province = province;
      if (city) conditions.city = city;

      const users = await db.findMany('users', conditions, {
        orderBy: 'created_at DESC',
        limit: pageSize,
        offset
      });

      const total = await db.count('users', conditions);

      // 解密用户信息（仅显示部分信息保护隐私）
      const decryptedUsers = users.map(user => {
        try {
          return {
            id: user.id,
            name: decrypt(user.name),
            phone: this.maskPhone(decrypt(user.phone)),
            province: user.province,
            city: user.city,
            district: user.district,
            is_anonymous: user.is_anonymous,
            created_at: user.created_at
          };
        } catch (e) {
          return {
            id: user.id,
            name: '解密失败',
            phone: '****',
            province: user.province,
            city: user.city,
            district: user.district,
            is_anonymous: user.is_anonymous,
            created_at: user.created_at
          };
        }
      });

      return {
        list: decryptedUsers,
        pagination: {
          page: parseInt(page),
          pageSize: parseInt(pageSize),
          total,
          totalPages: Math.ceil(total / pageSize)
        }
      };
    } catch (error) {
      throw new Error(`获取用户列表失败: ${error.message}`);
    }
  }

  // 掩码手机号
  static maskPhone(phone) {
    if (!phone || phone.length < 7) return phone;
    return phone.substring(0, 3) + '****' + phone.substring(phone.length - 4);
  }

  // 掩码身份证号
  static maskIdCard(idCard) {
    if (!idCard || idCard.length < 8) return idCard;
    return idCard.substring(0, 4) + '**********' + idCard.substring(idCard.length - 4);
  }

  // 更新用户信息
  async update(updateData) {
    try {
      // 加密需要更新的敏感信息
      const encryptedData = {};
      if (updateData.name) encryptedData.name = encrypt(updateData.name);
      if (updateData.phone) encryptedData.phone = encrypt(updateData.phone);
      if (updateData.id_card) encryptedData.id_card = encrypt(updateData.id_card);
      
      // 非敏感信息直接更新
      if (updateData.email) encryptedData.email = updateData.email;
      if (updateData.province) encryptedData.province = updateData.province;
      if (updateData.city) encryptedData.city = updateData.city;
      if (updateData.district) encryptedData.district = updateData.district;
      if (updateData.address) encryptedData.address = updateData.address;

      const affectedRows = await db.update('users', encryptedData, { id: this.id });
      
      if (affectedRows > 0) {
        Object.assign(this, updateData);
        return true;
      }
      return false;
    } catch (error) {
      throw new Error(`更新用户失败: ${error.message}`);
    }
  }

  // 获取用户的脱敏信息
  getSafeInfo() {
    return {
      id: this.id,
      name: this.name,
      phone: User.maskPhone(this.phone),
      id_card: this.id_card ? User.maskIdCard(this.id_card) : null,
      email: this.email,
      province: this.province,
      city: this.city,
      district: this.district,
      address: this.address,
      is_anonymous: this.is_anonymous,
      created_at: this.created_at
    };
  }

  // 转换为JSON格式
  toJSON() {
    return {
      id: this.id,
      name: this.name,
      phone: this.phone,
      email: this.email,
      province: this.province,
      city: this.city,
      district: this.district,
      address: this.address,
      is_anonymous: this.is_anonymous,
      created_at: this.created_at,
      updated_at: this.updated_at
    };
  }
}

module.exports = User; 